<template>
  <div class="c-image-upload">
    <el-upload
      ref="upload"
      :class="{ 'exced-limit': value && value.length >= limit }"
      :action="$UPLOAD_URL"
      :headers="extraheaders"
      :show-file-list="showFileList"
      :on-success="handleOnSuccess"
      :on-error="handleOnError"
      :file-list="fileList"
      v-bind="$attrs"
      class="img-uploader"
      accept="image/gif,image/jpeg,image/jpg,image/png,image/svg"
    >
      <slot slot="tip" name="tip" />
      <slot slot="trigger" name="trigger" />
      <div v-if="$attrs['list-type'] === 'picture-card'">
        <i class="el-icon-plus avatar-uploader-icon" />
      </div>
      <div slot="file" slot-scope="{file}">
        <img
          :src="file.url"
          class="el-upload-list__item-thumbnail"
        >
        <span class="el-upload-list__item-actions">
          <span
            class="el-upload-list__item-preview"
            @click="handleSeeDetail(file)"
          >
            <i class="el-icon-zoom-in" />
          </span>
          <!-- <span
            class="el-upload-list__item-delete"
            @click="handleDownload(file)"
          >
            <i class="el-icon-download" />
          </span> -->
          <span
            class="el-upload-list__item-delete"
            @click="handleOnRemove(file)"
          >
            <i class="el-icon-delete" />
          </span>
        </span>
      </div>
    </el-upload>
  </div>
</template>

<script>
import emitter from '@/mixins/emitter'
import { getToken } from '@/utils/auth'

export default {
  mixins: [emitter],
  model: {
    event: 'change'
  },
  props: {
    showFileList: {
      type: Boolean,
      default: true
    },
    limit: {
      type: Number,
      default: 1
    },
    value: {
      type: Array,
      default: () => [],
      required: true
    },
    headers: {
      type: Object,
      default: () => ({
        token: getToken()
      })
    }
  },
  data() {
    return {
      fileList: [],
      extraheaders: {
        ...this.headers,
        token: getToken(),
        currentOrgId: this.$store.state.user.orgId
      },
      dialogVisible: false
    }
  },
  watch: {
    value(val) {
      this.handleSetFileList()
    },
    headers(val) {
      this.extraData = {
        ...val,
        token: getToken(),
        currentOrgId: this.$store.state.user.orgId
      }
    }
  },
  created() {
    this.handleSetFileList()
  },
  methods: {
    handleSetFileList() {
      if (!this.value.length) {
        this.fileList = []
        return
      }
      const fileIsObject = this.value.some(item => typeof item === 'object')
      if (!fileIsObject) {
        this.fileList = []
        this.fileList = this.value.map(v => ({ url: v }))
      }
    },
    handleOnSuccess(response, file, fileList) {
      this.$message.success('上传成功')
      file.filePath = response.data
      const value = fileList.map(v => ({
        filePath: v.filePath,
        url: v.url
      }))
      this.dispatch('ElFormItem', 'el.form.change', value)
      this.$emit('on-change', value)
      this.$emit('change', value)
    },
    handleOnError(err, file, fileList) {
      this.$message.error(err.message)
    },
    // handleDownloadImg(file) {
    //   return downloadFile({ filePath: file }).then((res) => {
    //     this.fileList.push({
    //       filePath: file,
    //       url: res
    //     })
    //     this.$emit('on-change', this.fileList)
    //     this.$emit('change', this.fileList)
    //   }).catch(err => {
    //     this.$message.error(err.message)
    //   })
    // },
    // handleNoObserveAddFileList(file) {
    //   const index = Math.max(this.fileList.length, 0)
    //   this.fileList[index] = file
    // },
    handleOnRemove(file) {
      console.log('?????', file, this.$refs.upload.uploadFiles)

      const newData = this.$refs.upload.uploadFiles.filter(v => v.uid !== file.uid)
      this.fileList = newData
      this.$emit('on-change', newData)
      this.$emit('change', newData)
    },
    handleSeeDetail({ url }) {
      window.open(url)
    }
  }
}
</script>

<style lang="scss">
.c-image-upload {
  .img-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .exced-limit {
    .el-upload {
      display: none;
    }
  }
  .img-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .img-item {
     width: 100%;
     height: 100%;
     object-fit: cover;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 148px;
    height: 148px;
    line-height: 148px;
    text-align: center;
  }
  .avatar {
    width: 148px;
    height: 148px;
    display: block;
  }
}
</style>
